// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/common/base/bit_util.h>

namespace kumo::pollux::exec {
    // Describes a bit range inside a 64 bit hash number for use in
    // partitioning data.
    class HashBitRange {
    public:
        HashBitRange(uint8_t begin, uint8_t end)
            : begin_(begin), end_(end), fieldMask_(bits::lowMask(end - begin)) {
            POLLUX_CHECK_LE(begin_, end_);
            POLLUX_CHECK_LE(end_, 64);
        }

        HashBitRange() : HashBitRange(0, 0) {
        }

        int32_t partition(uint64_t hash, int32_t numPartitions) const {
            int32_t number = (hash >> begin_) & fieldMask_;
            return number < numPartitions ? number : -1;
        }

        int32_t partition(uint64_t hash) const {
            return (hash >> begin_) & fieldMask_;
        }

        uint8_t begin() const {
            return begin_;
        }

        uint8_t end() const {
            return end_;
        }

        uint8_t numBits() const {
            return end_ - begin_;
        }

        int32_t numPartitions() const {
            return 1 << numBits();
        }

        inline bool operator==(const HashBitRange &other) const {
            return std::tie(begin_, end_) == std::tie(other.begin_, other.end_);
        }

        inline bool operator!=(const HashBitRange &other) const {
            return !(*this == other);
        }

    private:
        // Low bit number of hash number bit range.
        uint8_t begin_;

        // Bit number of first bit above the hash number bit range.
        uint8_t end_;

        uint64_t fieldMask_;
    };
} // namespace kumo::pollux::exec
